﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;

namespace IntegratedOnBordDebug.UDPAsynQueue
{
    public sealed class CustomerUDPSocket
    {
        #region "Private Variables"
        private Socket _socket;
        private IBufferManagerProvider _bufferManager;
        #endregion

        #region "Public Properties"
        public Int32 Port { get; private set; }
        public Int32 MessagePrefixLength { get; set; }
        public IPAddress ListeningAddress { get; private set; }

        public bool AllowAddressReuse { get; private set; }
        #endregion

        #region "Constructors"
        private CustomerUDPSocket() { }
        public CustomerUDPSocket(String listeningAddress) : this(listeningAddress, 4444, null, null) { }
        public CustomerUDPSocket(String listeningAddress, Int32 port) : this(listeningAddress, port, null, null) { }
        public CustomerUDPSocket(Int32 port) : this("0.0.0.0", port, null, null) { }

        public CustomerUDPSocket(String listeningAddress, Int32 port, IBufferManagerProvider manager)
        {
            // Setup the port
            if (port <= 0)
            {
                throw new ArgumentException("Port number cannot be less than 0.");
            }
            else
            {
                this.Port = port;
            }

            // check the ip address
            if (String.IsNullOrEmpty(listeningAddress))
            {
                throw new Exception("The listening address supplied is not valid.");
            }
            this.ListeningAddress = IPAddress.Parse(listeningAddress);

            // check the interfaces
            _bufferManager = (manager == null) ? new DefaultBufferManager(100, 2048, null, null) : manager;

            // use a default message prefix
            this.MessagePrefixLength = 4;
        }
        #endregion

        #region "Event Handlers"
        #endregion

        #region "Internal handler methods"
        private void Receive()
        {
            SocketAsyncEventArgs args = _bufferManager.TakeNextSocketAsyncEventArgs();
            byte[] buff = _bufferManager.TakeNextBuffer();
            args.SetBuffer(buff, 0, buff.Length);
            args.Completed += PacketReceived;
            args.RemoteEndPoint = new IPEndPoint(IPAddress.Any, this.Port);

            try
            {
                if (!_socket.ReceiveMessageFromAsync(args))
                {
                    OnPacketReceived(args);
                }
            }
            catch
            {
                // we should only jump here when we disconnect all the clients.
            }
        }

        private void PacketReceived(object sender, SocketAsyncEventArgs e)
        {
            OnPacketReceived(e);
        }

        private void OnPacketReceived(SocketAsyncEventArgs e)
        {
            // Start a new Receive operation straight away
            Receive();

            // Now process the packet that we have already
            if (e.BytesTransferred <= MessagePrefixLength)
            {
                // Error condition, empty packet
                //this.LogProvider.Log(String.Format("Empty packet received from {0}. Discarding packet.", e.ReceiveMessageFromPacketInfo.Address.ToString()), "CustomerUDPSocket.OnPacketReceived", LogLevel.Minimal);
                ReleaseArgs(e);
                return;
            }

            //
            //  The buffer can occassionally be zero'd at this point in time
            //

            // Get the message length from the beginning of the packet.
            byte[] arrPrefix = new byte[MessagePrefixLength];
            Buffer.BlockCopy(e.Buffer, 0, arrPrefix, 0, MessagePrefixLength);
            Int32 messageLength = BitConverter.ToInt32(arrPrefix, 0);

            // the number of bytes remaining to store
            Int32 bytesToProcess = e.BytesTransferred - MessagePrefixLength;

            if (bytesToProcess < messageLength)
            {
                //this.LogProvider.Log(String.Format("Missing data from {0}. Discarding packet.", e.ReceiveMessageFromPacketInfo.Address.ToString()), "CustomerUDPSocket.OnPacketReceived", LogLevel.Minimal);
                ReleaseArgs(e);
                return;
            }

            // Create a data buffer
            byte[] data = new byte[messageLength];

            // Copy the remaining data to the data buffer on the user token
            Buffer.BlockCopy(e.Buffer, MessagePrefixLength, data, 0, messageLength);

            // Data is safely stored, so unhook the event and return the SocketAsyncEventArgs back to the pool
            ReleaseArgs(e);

            // Thread safe way of triggering the event
            var evnt = OnDataReceived;

            if (evnt != null)
            {
                evnt(e, new SocketDataEventArgs(data));
            }
        }

        private void ReleaseArgs(SocketAsyncEventArgs e)
        {
            e.Completed -= PacketReceived;
            _bufferManager.InsertSocketAsyncEventArgs(e);
            _bufferManager.InsertBuffer(e.Buffer);
        }
        #endregion

        #region "ISocket implicit implementation"
        public void Start()
        {
            //this.LogProvider.Log("Starting. Creating socket", "CustomerUDPSocket.Start", LogLevel.Verbose);
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, this.AllowAddressReuse);
            _socket.Bind(new IPEndPoint(this.ListeningAddress, this.Port));

            // use a default message prefix
            this.MessagePrefixLength = 4;

            // begin receiving packets
            Receive();

            //this.LogProvider.Log("Socket created. Listening for packets", "CustomerUDPSocket.Start", LogLevel.Verbose);
        }

        public void Stop()
        {
            // do a shutdown before you close the socket
            try
            {
                _socket.Shutdown(SocketShutdown.Both);
                //this.LogProvider.Log("Clean socket shutdown", "TCPSocket.CloseSocket", LogLevel.Verbose);
            }
            // throws if socket was already closed
            catch (Exception ex)
            {
                //this.LogProvider.Log("Error closing socket - " + ex.Message, "TCPSocket.CloseSocket", LogLevel.Minimal);
            }

            // Close the socket, which calls Dispose internally
            _socket.Close();
            //this.LogProvider.Log("Socket closed", "TCPSocket.CloseSocket", LogLevel.Verbose);
        }

        public event EventHandler<SocketDataEventArgs> OnDataReceived;
        #endregion
    }
}
